import ButtonManager from './ButtonManager.js'; // 导入按钮管理模块

const ComplianceNotice = {
  buttonId: 'complianceNotice', // 按钮 ID
  defaultText: '4. 获取商品合规通知并下架', // 默认按钮文本

  // 初始化函数
  init() {
    document.getElementById(this.buttonId).addEventListener('click', this.handleClick.bind(this)); // 绑定点击事件
  },

  // 点击事件处理函数
  async handleClick() {
    ButtonManager.updateButtonState(this.buttonId, '4. 获取商品合规通知并下架-处理中...', true); // 更新按钮状态为加载中
    ButtonManager.disableAllButtons(this.buttonId); // 禁用其他按钮

    try {
      const { mallId, antiContent } = await new Promise((resolve) => {
        chrome.storage.local.get(['mallId', 'antiContent'], resolve); // 从本地存储获取 mallId 和 antiContent
      });

      if (!mallId || !antiContent) {
        console.error("mallId 或 antiContent 未找到"); // 检查是否获取到必要参数
        return;
      }

      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); // 获取当前标签页

      const results = await chrome.scripting.executeScript({
        target: { tabId: tab.id }, // 注入脚本到当前标签页
        func: executeComplianceNotice, // 执行合规通知下架逻辑
        args: [mallId, antiContent], // 传递参数
      });

      if (results && results[0] && results[0].result) {
        console.log("下架商品合规通知完成，返回数据:", results[0].result); // 输出合规通知下架结果
      } else {
        console.error("未获取到有效数据"); // 输出错误信息
      }
    } catch (error) {
      console.error("下架商品合规通知失败:", error); // 捕获错误
    } finally {
      ButtonManager.resetButtonState(this.buttonId, this.defaultText); // 恢复按钮状态
      ButtonManager.enableAllButtons(); // 启用所有按钮
    }
  },
};

// 合规通知下架逻辑函数
function executeComplianceNotice(j_mallid, j_anti_content) {
  return new Promise((resolve, reject) => {
    console.log("开始执行商品合规通知下架逻辑...");
    console.log("接收到的参数:", { j_mallid, j_anti_content });

    let j_pageNum = 1;
    // let j_body = { "groupCode": "kj_goods_compliance", "pageSize": 100, "pageNum": 1, "readStatus": 0 }; // 未读
    let j_body = { "groupCode": "kj_goods_compliance", "pageSize": 100, "pageNum": 1}; // 所有
    let j_totalPage = 1;
    const j_regex = /SPU ID：(\d+)/;
    let j_successArr = []; // 下架成功数据

    let j_time = Math.floor(Math.random() * 2)*100 + 500

    let j_date = new Date();
    let j_year = j_date.getFullYear().toString();
    let j_month = (j_date.getMonth() + 1).toString();
    let j_day = j_date.getDate().toString();
     
    // 对月份和日期进行补零
    j_month = j_month.length === 1 ? '0' + j_month : j_month;
    day = j_day.length === 1 ? '0' + j_day : j_day;

    let j_dateTime = j_year + j_month + j_day;

    // 获取商品合规的通知spuid数据
    function j_msgBoxPage() {
      j_body.pageNum = j_pageNum;
      
      fetch("https://seller.kuajingmaihuo.com/bg/quick/api/merchant/msgBox/page", {
        method: 'POST',
        headers: {
          accept: '*/*',
          'accept-language': 'zh-CN,zh;q=0.9',
          'anti-content': j_anti_content,
          'cache-control': 'max-age=0',
          'content-type': 'application/json',
          mallid: j_mallid,
          priority: 'u=1, i',
          'sec-ch-ua': '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"macOS"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-origin'
        },
        referrer: 'https://seller.kuajingmaihuo.com/message?msgId=5936832726527&queryGroup=1',
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: JSON.stringify(j_body),
        mode: 'cors',
        credentials: 'include'
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          if (data.success) {
            let dataList = data.result.dataList;
            j_totalPage = data.result.totalPage;
            let spuIdsArr = [];
            dataList.forEach((item, index) => {
              let matchResult = item.content.match(j_regex);
              if (matchResult) {
                spuIdsArr.push(Number(matchResult[1]));
              }
            });

            if (j_pageNum <= j_totalPage) {
              j_pageNum++;
              setTimeout(function(){
                j_pageQuery(spuIdsArr);
              },j_time)
              
            } else {
              console.log('获取商品合规spu完成');
              resolve('获取商品合规spu完成',{success: spuIdsArr});
            }
          } else {
            console.log('获取商品合规spu失败');
            reject('获取商品合规spu失败');
          }
        })
        .catch(error => {
          console.error('There was a problem with your fetch operation:', error);
          reject(error);
        });
    }

    // 使用spuid查询获取skcid
    function j_pageQuery(arr) {
      if (arr.length === 0) {
        setTimeout(function(){
          j_msgBoxPage();
        },j_time)
        
        return;
      }
      let j_pageQuerybody = { "productIds": arr, "page": 1, "pageSize": 100 };
      fetch("https://seller.kuajingmaihuo.com/bg-visage-mms/product/skc/pageQuery", {
        method: 'POST',
        headers: {
          accept: '*/*',
          'accept-language': 'zh-CN,zh;q=0.9',
          'anti-content': j_anti_content,
          'cache-control': 'max-age=0',
          'content-type': 'application/json',
          mallid: j_mallid,
          priority: 'u=1, i',
          'sec-ch-ua': '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"macOS"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-origin'
        },
        referrer: 'https://seller.kuajingmaihuo.com/goods/product/list',
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: JSON.stringify(j_pageQuerybody),
        mode: 'cors',
        credentials: 'include'
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          if (data.success) {


            const allSkcIds = data.result.pageItems.map(item => item.productSkcId.toString());
            console.log(j_pageNum,'全部商品的skc', allSkcIds)
            setTimeout(function(){
              j_pageQuery2(arr,allSkcIds);
            },j_time)
            



            // console.log(data);
            // let skcidArr = [];
            // let pageItems = data.result.pageItems;
            // pageItems.forEach((item, index) => {
            //   skcidArr.push(item.productSkcId.toString());
            // });
            // j_submitFeedback(skcidArr, 0);
          } else {
            console.log('查询商品列表失败,' + data.errorMsg);
            reject('查询商品列表失败');
          }
        })
        .catch(error => {
          console.error('There was a problem with your fetch operation:', error);
          reject(error);
        });
    }

    // 通过spu查询已下架商品的skc
    function j_pageQuery2(arr,allSkcIds){
      fetch("https://seller.kuajingmaihuo.com/bg-visage-mms/product/skc/pageQuery", {
        method: 'POST',
        headers: {
          'anti-content': j_anti_content,
          'mallid': j_mallid,
          'content-type': 'application/json'
        },
        body: JSON.stringify({
          page: 1,
          pageSize: 100,
          skcSecondaryStatus: 1,
          skcTopStatus: 200,
          productIds: arr
        })
        
      })
      .then(res => res.json())
      .then(data => {
        if (data.success) {

          const isDownSkcIds = data.result.pageItems.map(item => item.productSkcId.toString()); // 已下架的skcid

          const isDownSet = new Set(isDownSkcIds); // 预先创建 Set
          const notDownSkcIds = allSkcIds.filter(id => !isDownSet.has(id)); // 未下架的商品skcid
          console.log(j_pageNum,'未下架商品的skc', notDownSkcIds)
          // 执行下架方法
          j_submitFeedback(notDownSkcIds, 0);
          
        } else {
          console.error('查询失败:', data.errorMsg);
          setTimeout(function(){
            j_msgBoxPage();
          },j_time)
        }
      })
      .catch(error => {
        console.error('查询异常:', error);
        setTimeout(function(){
          j_msgBoxPage();
        },j_time)
      });
    }

    // 下架商品
    let j_submitFeedbackErrorArr = [];
    function j_submitFeedback(arr, arrIndex) {
      if (arrIndex >= arr.length) {
        setTimeout(function(){
          j_msgBoxPage();
        },j_time)
        return;
      }

      let arri = arrIndex;
      
      fetch("https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/ultraman/FeedbackMmsExecuteRpcService/submitFeedback", {
        method: 'POST',
        headers: {
          accept: '*/*',
          'accept-language': 'zh-CN,zh;q=0.9',
          'anti-content': j_anti_content,
          'cache-control': 'max-age=0',
          'content-type': 'application/json',
          mallid: j_mallid,
          priority: 'u=1, i',
          'sec-ch-ua': '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"macOS"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-origin'
        },
        referrer: 'https://seller.kuajingmaihuo.com/goods/product/list',
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: JSON.stringify({
          feedbackType: 1,
          productSkcId: arr[arri],
          feedbackProblemType: 27,
          remark: "图片上传错误，申请下架" + j_dateTime,
          feedbackDimension: 2
        }),
        mode: 'cors',
        credentials: 'include'
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          arri++;
          if (data.success) {
            j_successArr.push(arr[arrIndex]);
            console.log(j_successArr.length, '下架成功', j_successArr);
          } else {
            console.log((arr[arrIndex] + '/下架失败，' + data.errorMsg));
            j_submitFeedbackErrorArr.push(arr[arrIndex]);
          }

          if (arr.length <= arri) {
            setTimeout(function(){
              j_msgBoxPage();
            },j_time)
            let newsubmitFeedbackErrorArr = j_submitFeedbackErrorArr.map(Number);
            console.log(j_submitFeedbackErrorArr.length + '下架失败数据(skcid)：', JSON.stringify(newsubmitFeedbackErrorArr));
            resolve('下架完成',{success:arr[arri]});
          } else {
            setTimeout(function(){
              j_submitFeedback(arr, arri);
            },j_time)
            
          }
        })
        .catch(error => {
          console.error('There was a problem with your fetch operation:', error);
          reject(error);
        });
    }

    // 开始执行逻辑
    setTimeout(function(){
      j_msgBoxPage();
    },j_time)
    
  });
}

export default ComplianceNotice; // 导出模块